//
//  SLBaseVC.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/4.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import UIKit
import WebKit
import DZNEmptyDataSet
import SwiftyJSON
import JXSegmentedView
import AppTrackingTransparency
import AdSupport
import CoreLocation

class SLBaseVC: UIViewController {
    var id:String = ""
    var json:JSON?
    var startDate:Int = 0
    var hiddenTab:Bool = false
    
    lazy var navigationView:SLNavigationBar = {
        let v = SLNavigationBar(frame: CGRectZero)
        self.view.addSubview(v)
        v.isHidden = true
        v.snp.makeConstraints { make in
            make.left.right.top.equalTo(0)
            make.height.equalTo(DevConfig.nav_height)
        }
        v.onClickLeftButton = { [weak self] in
            if let ss  = self {
                ss.navigationLeftBtnClick()
            }
        }
        return v
    }()
    init(id:String = "",hiddenTab:Bool? = true,json:JSON? = nil) {
        super.init(nibName: nil, bundle: nil)
        self.id = id
        self.hiddenTab = hiddenTab!
        self.json = json

    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.isHidden = self.hiddenTab
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 为self创建弱引用对象
        
        self.startDate = Int(Date().timeIntervalSince1970)
        self.navigationController?.isNavigationBarHidden = true
        
        view.backgroundColor = .white
        NotificationCenter.default.addObserver(self, selector: #selector(loginEventAction), name: NSNotification.Name(loginInEvent), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(logoutEventAction), name: NSNotification.Name(loginOutEvent), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(NetworkReachEventAction), name: NSNotification.Name("NetworkReachability"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(NetworkBreakEventAction), name: NSNotification.Name("NetworkDisconnected"), object: nil)
        checkLocationServices()
    }
    override var title: String?{
        didSet{
            self.navigationView.title = title
            self.navigationView.isHidden = false
        }
    }
    
    @objc func NetworkReachEventAction(){
         
    }
    @objc func NetworkBreakEventAction(){
        
    }
    @objc func loginEventAction(){
        
    }
    @objc func logoutEventAction(){
         
     }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        view.endEditing(true)
        
        self.locationManager.stopUpdatingLocation()

        NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
    }
    @objc func navigationLeftBtnClick()->(){
        if self.navigationController?.viewControllers.count == 1 {
            navigationController?.dismiss(animated: true, completion: nil)
        }else{
            navigationController?.popViewController(animated: true)
        }
    }
    func checkLocationServices() {
        self.locationManager.startUpdatingLocation()
    }

    lazy var locationManager:CLLocationManager = {
        let pt = CLLocationManager()
        pt.delegate = self    //位置管理器代理人是view controller对象.希望view controller能通过实现CLLocationManagerDelegate协议中的方法,获取到当前用户位置信息
        pt.desiredAccuracy = kCLLocationAccuracyBest   
        pt.requestWhenInUseAuthorization()    //请求当用户正在使用app的时候允许后台得到用户位置.只会弹出来一次
        return pt
    }()
    lazy var backgroundImageV:UIImageView = {
        let imageV = UIImageView(frame: CGRect(x: 0, y: 0, width: DevConfig.width, height: DevConfig.heigth))
        imageV.contentMode = .scaleToFill
        self.view.addSubview(imageV)
        self.view.sendSubviewToBack(imageV)
        return imageV
    }()
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        backgroundImageV.snp.makeConstraints { make in
            make.left.right.top.bottom.equalTo(0)
        }
    }
}
extension SLBaseVC: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}
extension SLBaseVC: CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
           if let location = manager.location {
               let geocoder = CLGeocoder()  // 新增地理编码器
               let loc = CLLocation(latitude: Double(location.coordinate.latitude), longitude: Double(location.coordinate.longitude))
               geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
                   if error != nil {
                   } else if let placemarks = placemarks {
                       let latitude = "\(location.coordinate.latitude)"
                       let longitude = "\(location.coordinate.longitude)"
                       
                       __setValue(value: latitude, key: "latitude")
                       __setValue(value: longitude, key: "longitude")
                   }
               }
               // 获取到位置信息后，停止更新位置，节省电量
               manager.stopUpdatingLocation()

           }
       }
    func locationManager(_ manager: CLLocationManager, didFailRangingFor beaconConstraint: CLBeaconIdentityConstraint, error: Error) {
        print(error)
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
        let time = _date_date_string(date: Date())
        if(__valueForKey(key: time) == nil) {
            __setValue(value: 1, key: time)
            self.showLocationServicesDeniedAlert()
        }else{
            
        }
    }
    // 实现代理方法，处理权限请求的结果
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
//        manager.stopUpdatingLocation()
        switch status {
        case .authorizedWhenInUse, .authorizedAlways,.restricted:
            print("定位权限被授予")
            // 开始获取位置信息
        case .denied:
            print("定位权限被拒绝")
            // 引导用户到设置去开启权限
            DispatchQueue.main.async {
//                self.bottomBtn.isHidden = false
                
            }
        default:
            break
        }
    }
     
        // 弹出警告，引导用户到设置去开启定位服务权限
        func showLocationServicesDeniedAlert() {
            guard let status = __valueForKey(key: kFlush) as? Int,
                  status == 1 else{return}
            
            if locationManager.authorizationStatus == .denied{
                let alertController = UIAlertController(
                    title: "The location service is closed",
                    message: "The current application collects your location information, uses it for loan risk assessment, and recommends personalized products to you. You can open Settings-Privacy System and set it to off at any time.",
                    preferredStyle: .alert)
                
                alertController.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: { _ in
                }))
                alertController.addAction(UIAlertAction(title: "setting", style: .default, handler: { _ in
                    if let appSettings = URL(string: UIApplication.openSettingsURLString) {
                        UIApplication.shared.open(appSettings, options: [:]) { _ in
                        }
                    }
                }))
                self.present(alertController, animated: true, completion: nil)
            }
            
        }

}
extension SLBaseVC: DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func backgroundColor(forEmptyDataSet scrollView: UIScrollView!) -> UIColor! {
        return UIColor.clear
    }

//    func buttonBackgroundImage(forEmptyDataSet scrollView: UIScrollView!, for state: UIControl.State) -> UIImage! {
//        return UIImage(named: "addbutton")
//    }
//
//    func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControl.State) -> NSAttributedString! {
//        return GFLanguageAdapter.localization(key: "添加").toAtrributeString(color: .white, font: GFFontConfig.medium15)
//    }
    func emptyDataSet(_ scrollView: UIScrollView!, didTap button: UIButton!) {
      
    }
//    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
//        return GFLanguageAdapter.localization(key: "暂无数据").toAtrributeString(color: rgba(51, 51, 51), font: GFFontConfig.medium16)
//    }
    func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        return NSAttributedString(string: "nodata", attributes: nil)
    }
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return IMAGE("为空")
    }

    func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
        return -60
    }
    func spaceHeight(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
        return 16
    }
    
    func emptyDataSetShouldFade(in scrollView: UIScrollView!) -> Bool {
        return true
    }
    
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
        
        return true
    }
}
extension SLBaseVC: UIGestureRecognizerDelegate {
//    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
//        if gestureRecognizer == navigationController?.interactivePopGestureRecognizer {
//            // 在这里可以添加您的逻辑，来判断是否拦截左滑返回手势
//            return true // 返回false表示拦截手势
//        }
//        return true
//    }
}
